package common

import (
	"backend/config"
	"crypto/tls"
	"fmt"
	"net/smtp"
)

type Mail struct {
	From    string
	To      []string
	Subject string
	Body    string
}

func SendMail(mail Mail) error {
	// SMTP服务器配置
	smtpServer := config.Configs.SMTP.Server
	smtpPort := config.Configs.SMTP.Port
	username := config.Configs.SMTP.Username
	password := config.Configs.SMTP.Password

	// 认证信息
	auth := smtp.PlainAuth("", username, password, smtpServer)

	// TLS配置
	tlsConfig := &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         smtpServer,
	}

	// 连接SMTP服务器
	conn, err := tls.Dial("tcp", fmt.Sprintf("%s:%s", smtpServer, smtpPort), tlsConfig)
	if err != nil {
		return err
	}

	client, err := smtp.NewClient(conn, smtpServer)
	if err != nil {
		return err
	}

	// 认证
	if err = client.Auth(auth); err != nil {
		return err
	}

	// 设置发件人
	if err = client.Mail(mail.From); err != nil {
		return err
	}

	// 设置收件人
	for _, to := range mail.To {
		if err = client.Rcpt(to); err != nil {
			return err
		}
	}

	// 发送邮件内容
	w, err := client.Data()
	if err != nil {
		return err
	}

	msg := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s",
		mail.From, mail.To[0], mail.Subject, mail.Body)

	_, err = w.Write([]byte(msg))
	if err != nil {
		return err
	}

	err = w.Close()
	if err != nil {
		return err
	}

	client.Quit()
	return nil
}
